import ColorTool from "@/utils/color-tool";
import appConfig from "../../app.config";

export function addStyleNode(styleStr: string, id: string) {
  const existNode = document.querySelector(`#${id}`);
  const styleNode = existNode || document.createElement("style");
  styleNode.innerHTML = styleStr;
  if (!existNode) {
    styleNode.id = id;
    document.getElementsByTagName("head")[0].appendChild(styleNode);
  }
}

/* "rgb(255, 153, 28)" 这种格式也是可以转换的 */
export default function changeTheme(themeColor: string = "#276ff5") {
  const colorTool = new ColorTool(themeColor);

  const colorArr = colorTool
    .getColorPalettes()
    .map(
      (color: string, index: number) =>
        `--${appConfig.APP_NAME}-color-theme-${index + 1}: ${color};`
    );
  const styleStr = `
      :root {
        --${appConfig.APP_NAME}-color-theme: ${themeColor};
        ${colorArr.join("\n        ")}
      }
    `;
  addStyleNode(styleStr, `__${appConfig.APP_NAME}-theme-css-variable`);
}
